package com.competition.commgr.service.impl;

import java.util.List;

import com.competition.commgr.domain.*;
import com.competition.commgr.domain.vo.RegistrationVo;
import com.competition.commgr.service.*;
import com.competition.common.core.domain.entity.SysDictData;
import com.competition.common.utils.SecurityUtils;
import com.competition.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.competition.commgr.mapper.RegistrationMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 报名Service业务层处理
 * 
 * @author cui
 * @date 2025-02-01
 */
@Service
public class RegistrationServiceImpl implements IRegistrationService 
{
    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private ITeamService teamService;

    @Autowired
    private IMembersService membersService;

    @Autowired
    private ICompetitionsessionsService competitionsessionsService;

    @Autowired
    private IRegistrationReviewService registrationReviewService;

    @Autowired
    private ISysDictDataService  sysDictDataService;

    @Override
    @Transactional
    public int insertRegistration(RegistrationVo registration)
    {
        try {
            //插入Team表
            Team team = new Team();
            team.setTeamName(registration.getTeamName());
            teamService.insertTeam(team);
            long teamId = team.getTeamId();
            registration.setTeamId(teamId);

            //往Members表中插入参赛成员
            Long[] memberIds = registration.getMemberIds();
            if (memberIds != null) {
                for (long userId : memberIds) {
                    //插入Members表
                    Members members = new Members();
                    members.setTeamId(teamId);
                    members.setUserId(userId);
                    members.setTeamType(112L); //参赛团队类型对应的字典编码为112
                    membersService.insertMembers(members);
                }
            }

            //往Members表中插入指导成员
            Long[] coachIds = registration.getCoachIds();
            if (coachIds != null) {
                for (long userId : coachIds) {
                    //插入Members表
                    Members members = new Members();
                    members.setTeamId(teamId);
                    members.setUserId(userId);
                    members.setTeamType(111L);//指导团队类型对应的字典编码为111
                    membersService.insertMembers(members);
                }
            }

            //根据赛事id、赛项id、年份、届次到CompetitionSession表中查询到对应的ComSessionId
            Competitionsessions competitionsessions = new Competitionsessions();
            competitionsessions.setCompetitionId(registration.getCompetitionId());
            competitionsessions.setComItemId(registration.getComItemId());
            competitionsessions.setYear(registration.getYear());
            competitionsessions.setSessionNum(registration.getSessionNum());
            List<Competitionsessions> competitionsessionList = competitionsessionsService.selectCompetitionsessionsList(competitionsessions);
            if (competitionsessionList != null && competitionsessionList.size() > 0) {
                registration.setComSessionId(competitionsessionList.get(0).getSessionId());
            }

            //写入报名表
            int result = registrationMapper.insertRegistration(registration);
            if (result <= 0) {
                throw new RuntimeException("报名信息插入失败");
            }

            //确保获取到自动生成的报名id
            Long regId = registration.getRegId();
            if (regId == null) {
                throw new RuntimeException("无法获取报名ID");
            }
            System.out.println("regId:" + regId);

            //写入报名审核表：一次性全部写入，比如有两个审核环节，那么就会插入两个审核记录。审核环节从sys_dict_data中获取，其dict_type为approval_step
            List<SysDictData> approvalStepList = sysDictDataService.selectDictDataList(new SysDictData("approval_step"));
            if (approvalStepList == null || approvalStepList.isEmpty()) {
                throw new RuntimeException("未找到审批步骤配置");
            }

            for (SysDictData sysDictData : approvalStepList) {
                RegistrationReview registrationReview = new RegistrationReview(regId, "pending", sysDictData.getDictLabel(), SecurityUtils.getUserId(), "");
                int reviewResult = registrationReviewService.insertRegistrationReview(registrationReview);
                if (reviewResult <= 0) {
                    throw new RuntimeException("审批记录插入失败: " + sysDictData.getDictLabel());
                }
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("报名创建失败: " + e.getMessage(), e);
        }
//        try {
//            //插入Team表
//            Team team = new Team();
//            team.setTeamName(registration.getTeamName());
//            teamService.insertTeam(team);
//            long teamId = team.getTeamId();
//            registration.setTeamId(teamId);
//
//            //往Members表中插入参赛成员
//            Long[] memberIds = registration.getMemberIds();
//            for (long userId : memberIds) {
//                //插入Members表
//                Members members = new Members();
//                members.setTeamId(teamId);
//                members.setUserId(userId);
//                members.setTeamType(112L); //参赛团队类型对应的字典编码为112
//                membersService.insertMembers(members);
//            }
//
//            //往Members表中插入指导成员
//            Long[] coachIds = registration.getCoachIds();
//            for (long userId : coachIds) {
//                //插入Members表
//                Members members = new Members();
//                members.setTeamId(teamId);
//                members.setUserId(userId);
//                members.setTeamType(111L);//指导团队类型对应的字典编码为111
//                membersService.insertMembers(members);
//            }
//
//            //根据赛事id、赛项id、年份、届次到CompetitionSession表中查询到对应的ComSessionId
//            Competitionsessions competitionsessions = new Competitionsessions();
//            competitionsessions.setCompetitionId(registration.getCompetitionId());
//            competitionsessions.setComItemId(registration.getComItemId());
//            competitionsessions.setYear(registration.getYear());
//            competitionsessions.setSessionNum(registration.getSessionNum());
//            List<Competitionsessions> competitionsessionList = competitionsessionsService.selectCompetitionsessionsList(competitionsessions);
//            if (competitionsessionList.size() > 0) {
//                registration.setComSessionId(competitionsessionList.get(0).getSessionId());
//            }
//
//            //写入报名表
//            registrationMapper.insertRegistration(registration);
//            //获取自动生成的报名id
//            Long regIgId = registration.getRegId();
//            System.out.println("regIgId:" + regIgId);
//            //写入报名审核表：一次性全部写入，比如有两个审核环节，那么就会插入两个审核记录。审核环节从sys_dict_data中获取，其dict_type为approval_step
//            List<SysDictData> approvalStepList = sysDictDataService.selectDictDataList(new SysDictData("approval_step"));
//            for (SysDictData sysDictData : approvalStepList) {
//                RegistrationReview registrationReview = new RegistrationReview(regIgId, "pending", sysDictData.getDictLabel(), SecurityUtils.getUserId(), "");
//                registrationReviewService.insertRegistrationReview(registrationReview);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return 0;
//        }
//        return 1;
    }


    /**
     * 查询报名
     * 
     * @param regId 报名主键
     * @return 报名
     */
    @Override
    public Registration selectRegistrationByRegId(Long regId)
    {
        return registrationMapper.selectRegistrationByRegId(regId);
    }

    /**
     * 查询报名列表
     * 
     * @param registration 报名
     * @return 报名
     */
    @Override
    public List<RegistrationVo> selectRegistrationVoList(Registration registration)
    {
        List<RegistrationVo> list = registrationMapper.selectRegistrationVoList(registration);
        for (RegistrationVo registrationVo : list) {
            RegistrationReview registrationReview =  new RegistrationReview();
            registrationReview.setRegId(registrationVo.getRegId());
            //查询对应的审核记录
            List<RegistrationReview> registrationReviewList = registrationReviewService.
                    selectRegistrationReviewList(registrationReview);
            registrationVo.setRegistrationReviews(registrationReviewList);
        }
        return list;
    }



    /**
     * 修改报名
     * 
     * @param registration 报名
     * @return 结果
     */
    @Override
    public int updateRegistration(Registration registration)
    {
        return registrationMapper.updateRegistration(registration);
    }

    /**
     * 批量删除报名
     * 
     * @param regIds 需要删除的报名主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteRegistrationByRegIds(Long[] regIds)
    {
        for (Long regId : regIds) {

            Registration registration = registrationMapper.selectRegistrationByRegId(regId);
            //删除Team表
            teamService.deleteTeamByTeamId(registration.getTeamId());
            //删除Members表中外键为team_id的数据，这个操作在数据库中设置了外键约束的级联删除操作，无需手动删除
        }

        return registrationMapper.deleteRegistrationByRegIds(regIds);
    }

    /**
     * 删除报名信息
     * 
     * @param regId 报名主键
     * @return 结果
     */
    @Override
    public int deleteRegistrationByRegId(Long regId)
    {
        return registrationMapper.deleteRegistrationByRegId(regId);
    }
}
